#!/usr/bin/python  #-*- coding:utf-8 -*-  
__author__ = 'xujian'
############################  
#File Name: web.py
#Author: orangleliu  
#Mail: orangleliu@gmail.com  
#Created Time: 2018-01-25 10:37:45
############################ 
import tornado.ioloop
import tornado.web
from tornado.options import options, define
from tornado import gen
import hashlib
import json
import logging
from tornado.ioloop import IOLoop

define("port", default=9888, help="TCP port to listen on")
logger = logging.getLogger(__name__)

appsecret="12345678912345678912345678912345"

def check_sign(sign,data):
    l = list(data)
    l.sort()
    s = "".join(l)

    sha = hashlib.sha1(s)
    encrypts = sha.hexdigest()
    logger.info("old sign:%s",sign)
    logger.info("new sign:%s",encrypts)
    if sign == encrypts:
        return True
    else:
        return False
msg = {
        '0000':'',
        '0008':'Invalid request.',
        '0009':'Unsupport params.',
        '2001':'The identifier does not exist.',
        '2002':'The resource type is not specified.',
        '2003':'Page is not specified.',
        '2004':'Id of the resource is empty.',
        '2005':'The resource does not exist.'
        }

class ExampleHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling ExampleHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                else:
                    data =  self.request.body + timestamp + appsecret
                    if not check_sign(sign,data):
                        code = "0008"
                    else:
                        code = "0000"
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result))
        self.finish()
    def get(self):
        self.post()

class ActiveListHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling ActiveListHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                data =  self.request.body + timestamp + appsecret
                if not check_sign(sign,data):
                    code = "0008"
                else:
                    code = "0000"

                    datajson = json.loads(self.request.body)
                    logger.info('datajson :%s',datajson)
                    logger.info('datajson bundle:%s',datajson['bundle'])

                    if 'bundle' in datajson and 'platform' in datajson:
                        if datajson['bundle'] == 'com.yq.dota' and datajson['platform'] == '0':
                            code = '0000'
                            resource_type = datajson['resource_type']
                            if len(resource_type) == 0:
                                code = '2002'
                            else:
                                with open('/opt/activelist.json','r') as fp:
                                    webdata = json.load(fp, encoding="utf-8")
                                result['inner_games'] = webdata['inner_games']
                        else:
                            code = '2001'
                    else:
                        code = '0008'
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result,indent = 4,ensure_ascii=False))
        self.finish()

    def get(self):
        self.post()

class InActiveListHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling InActiveListHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                data =  self.request.body + timestamp + appsecret
                if not check_sign(sign,data):
                    code = "0008"
                else:
                    code = "0000"

                    datajson = json.loads(self.request.body)
                    logger.info('datajson :%s',datajson)
                    logger.info('datajson bundle:%s',datajson['bundle'])

                    if 'bundle' in datajson  and 'platform' in datajson:
                        if'page' in datajson:
                            if datajosn and datajson['platform'] == '0' and datajson['bundle'] == 'com.yq.dota':
                                code = '0000'
                                resource_type = datajson['resource_type']
                                if len(resource_type) == 0:
                                    code = '2002'
                                else:
                                    with open('/opt/inactivelist.json','r') as fp:
                                        webdata = json.load(fp, encoding="utf-8")
                                    result['games'] = webdata['games']
                            else:
                                code = '2001'
                        else:
                            code = '2003'
                    else:
                        code = '0008'
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result,indent = 4,ensure_ascii=False))
        self.finish()

    def get(self):
        self.post()

enablee = 1

class PromoteHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling PromoteHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                data =  self.request.body + timestamp + appsecret
                if not check_sign(sign,data):
                    code = "0008"
                else:
                    code = "0000"

                    #logger.info('datajson :%s',datajson)
                    datajson = json.loads(self.request.body)
                    logger.info('datajson :%s',datajson)
                    logger.info('datajson bundle:%s',datajson['bundle'])
                    if 'bundle' in datajson:
                        if datajson['bundle'] == 'com.yq.dota':
                            code = '0000'
                            global enablee
                            if enablee == 1:
                                result['enable_promote'] = '0'
                                enablee = 0
                            else:
                                result['enable_promote'] = '1'
                                enablee = 1
                        else:
                            code = '2001'
                    else:
                        code = '0008'
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result))
        self.finish()

    def get(self):
        self.post()

class ResourceShowHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling ResourceShowHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                data =  self.request.body + timestamp + appsecret
                if not check_sign(sign,data):
                    code = "0008"
                else:
                    code = "0000"
                    datajson = json.loads(self.request.body)
                    logger.info('datajson :%s',datajson)
                    logger.info('datajson bundle:%s',datajson['bundle'])
                    if 'bundle' in datajson and 'platform' in datajson and 'resource_ids' in datajson and 'device_id' in datajson:
                        if datajson['bundle'] == 'com.yq.dota' and datajson['device_id'] == 'abcdefghigk' and datajson['platform'] == '0':
                            code = '0000'
                            resource_ids = datajson['resource_ids']
                            if len(resource_ids) == 0:
                                code = '2004'
                        else:
                            code = '2001'
                    else:
                        code = '0008'
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result))
        self.finish()

    def get(self):
        self.post()

class ResourceClickHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling ResourceClickHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                data =  self.request.body + timestamp + appsecret
                if not check_sign(sign,data):
                    code = "0008"
                else:
                    code = "0000"

                    datajson = json.loads(self.request.body)
                    logger.info('datajson :%s',datajson)
                    logger.info('datajson bundle:%s',datajson['bundle'])
                    if 'bundle' in datajson and 'platform' in datajson and 'resource_ids' in datajson and 'device_id' in datajson:
                        if datajson['bundle'] == 'com.yq.dota' and datajson['device_id'] == 'abcdefghigk' and datajson['platform'] == '0':
                            code = '0000'
                            resource_ids = datajson['resource_ids']
                            if len(resource_ids) == 0:
                                code = '2004'
                        else:
                            code = '2001'
                    else:
                        code = '0008'
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result))
        self.finish()

    def get(self):
        self.post()

class GameStartHandler(tornado.web.RequestHandler):
    def post(self):
        result = {}
        logging.info('calling GameStartHandler')
        logger.info('body:%s',self.request.body)
	try:
		timestamp = self.get_argument("timestamp")
		sign = self.get_argument("sign")
                logger.info('timestamp:%s',timestamp)
                logger.info('sign:%s',sign)
		if not sign or not timestamp:
                    code = "0008"
                data =  self.request.body + timestamp + appsecret
                if not check_sign(sign,data):
                    code = "0008"
                else:
                    code = "0000"

                    datajson = json.loads(self.request.body)
                    logger.info('datajson :%s',datajson)
                    logger.info('datajson bundle:%s',datajson['bundle'])
                    if 'bundle' in datajson and 'platform' in datajson and 'resource_ids' in datajson and 'device_id' in datajson:
                        if datajson['bundle'] == 'com.yq.dota' and datajson['device_id'] == 'abcdefghigk' and datajson['platform'] == '0':
                            code = '0000'
                            resource_ids = datajson['resource_ids']
                            if len(resource_ids) == 0:
                                code = '2004'
                        else:
                            code = '2001'
                    else:
                        code = '0008'
	except Exception as e:
                code = "0008"
		logger.error('error :%s',str(e))

        result['code'] = code
        result['msg'] = msg[code]
        self.write(json.dumps(result))
        self.finish()

    def get(self):
        self.post()
	

def make_app():
    return tornado.web.Application([
        (r"^/game/example", ExampleHandler),
        (r"^/game/promote/enable", PromoteHandler),
        (r"^/game/promote/active/list", ActiveListHandler),
        (r"^/game/promote/inactive/list", InActiveListHandler),
        (r"^/statics/resource/show", ResourceShowHandler),
        (r"^/statics/resource/click", ResourceClickHandler),
        (r"^/statics/game/start", GameStartHandler)
    ])

def log_TimedRotatingFileHandler():
    fmt_str ='%(asctime)s PID:%(process)d %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
    logging.basicConfig()

    fileshandle = logging.handlers.TimedRotatingFileHandler('logs/server', "MIDNIGHT", 1, 30) 
    fileshandle.setLevel(logging.DEBUG)
    formatter = logging.Formatter(fmt_str)
    fileshandle.setFormatter(formatter)
    logging.getLogger('').addHandler(fileshandle)

if __name__ == "__main__":
    import os
    os.chdir('/opt')
    log_TimedRotatingFileHandler()
    options.parse_command_line()
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
